package com.gome.bg.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

	public static String signBySec(String content, String mackey) {

		String orgcontent = content + mackey;
		return md5(orgcontent.getBytes());
	}

	public boolean verify(String content, String sign, String publicKey) {
		return true;
	}

	public boolean verifysign(String orgdata, String sign, String mackey) {
		try {
			String md5ret = md5((orgdata + mackey).getBytes());
			if (md5ret.equals(sign))
				return true;
			else
				return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 
	 * @param d
	 *            byte[]
	 * @return String
	 */
	public static String ByteArrayToHexString(byte[] d) {
		if (d == null)
			return "";
		if (d.length == 0)
			return "";

		int len = d.length * 2;
		byte[] strData = new byte[len];
		for (int i = 0; i < strData.length; i++)
			strData[i] = (byte) '0';
		byte[] data = new byte[d.length + 1];
		data[0] = 0;
		System.arraycopy(d, 0, data, 1, d.length);
		BigInteger bi = new BigInteger(data);
		byte[] src = bi.toString(16).getBytes();
		int offset = strData.length - src.length;
		len = src.length;
		System.arraycopy(src, 0, strData, offset, len);
		return new String(strData);
	}

	/**
	 * 
	 * @param algorithm
	 *            String MD5/SHA
	 * @param b
	 *            byte[]
	 * @return byte[]
	 */
	public static byte[] hashData(String algorithm, byte[] b)
			throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance(algorithm);
		md.update(b);
		byte[] digest = md.digest();
		return digest;
	}

	/**
	 * 
	 * @param algorithm
	 *            String MD5/SHA
	 * @param b
	 *            byte[]
	 * @return byte[]
	 */
	public static String md5(byte[] b) {
		try {
			byte[] a = hashData("MD5", b);
			return ByteArrayToHexString(a);
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	public static String sign(String content, String mackey) {
		String orgcontent = content + mackey;
		return md5(orgcontent.getBytes());
	}

	public static void main(String[] args) {

	}

}
